﻿
//***********************************************************************
// * Module:   MsjZaYqbzHandler
// * 作者:  曹荣芝
// * Modified: 2013/5/29
// * Purpose: Definition of the Class MsjZaYqbzHandler 业务逻辑处理Handler类
// ***********************************************************************/

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using XWG.Framework.MSException;
using XWG.Framework.AuthUtility;
using XWG.Framework.AuthEntity;
using XWG.Framework.AuthSPConst;
using XWG.Framework.AuthBLL;
using XWG.JWBST.JWBSTEntity;
using XWG.JWBST.JWBSTSPConst;
using System.Web.Script.Serialization;
using System.Data;
using XWG.Framework.Query;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using XWG.JWBST.JWBSTBLL;
using System.IO;
using JWBSTAPP.CommonClass;
using XWG.Framework;
namespace JWBSTAPP.AjaxServer
{
    /// <summary>
    /// MsjZaYqbzHandler 的摘要说明
    /// </summary>
    public class MsjZaYqbzHandler : JWBSTAPP.CommonClass.HttpHandlerBase, System.Web.SessionState.IRequiresSessionState
    {

        #region 添加记录
        /// <summary>
        /// 添加记录
        /// </summary>
        protected void AddRecord()
        {
            HttpContext context = HttpContext.Current;
            context.Response.ContentType = "text/plain";
            ResultModel mResultModel = new ResultModel(); //初始化返回类型
            //对Session的处理
            var mUser = AppOrganizatiOnUserBLL.Load(context.Session["UserID"].ToString());
            var mOrg = AppOrganizatiOnBLL.Load(mUser.OrgnaId);
            try
            {
                var id = Guid.NewGuid().ToString();
                MsjZaYqbz mMsjZaYqbz = new MsjZaYqbz();
                mMsjZaYqbz.Ryid = id; //主键
                mMsjZaYqbz.Xm = context.Request.Form["texXm"]; //养犬人姓名
                mMsjZaYqbz.Zw = context.Request.Form["texZw"]; //联系电话
                mMsjZaYqbz.Sfzh = context.Request.Form["texSfzh"]; //身份证号
                mMsjZaYqbz.Email = context.Request.Form["texEmail"]; //Email地址
                mMsjZaYqbz.Yqrzz = context.Request.Form["texYqrzz"]; //养犬人住址(请精确到门牌号码）
                mMsjZaYqbz.Sjdwid = context.Request.Form["texSjdwid"]; //上级单位ID(所属分局和市局）
                mMsjZaYqbz.Pcsid = context.Request.Form["texPcsid"]; //单位ID
                mMsjZaYqbz.Qz = context.Request.Form["texQz"]; //犬种
                mMsjZaYqbz.Ms = context.Request.Form["texMs"]; //毛色
                mMsjZaYqbz.Jg = Convert.ToDecimal(context.Request.Form["texJg"]); //肩高(cm)
                mMsjZaYqbz.Tc = Convert.ToDecimal(context.Request.Form["texTc"]); //体长(cm)
                mMsjZaYqbz.Xb = context.Request.Form["selXb"]; //犬只性别（1雄，0雌）
                mMsjZaYqbz.Qm = context.Request.Form["texQm"]; //犬名
                //mMsjZaYqbz.Zp = context.Request.Form["texZp"]; //犬只照片
                mMsjZaYqbz.Cjsj = DateTime.Now.ToString(); //创建时间(2013-05-28 09:13:01)
                mMsjZaYqbz.Cjr = mUser.AreaId; //创建人(人员ID)
                mMsjZaYqbz.Cjrdw = mOrg.OrgnaCode; //创建单位(单位ID)
                mMsjZaYqbz.Enabled = Enabled.TRUE; //是否有效（1有效，0无效）
                mMsjZaYqbz.Movesign = "0"; //是否传输（1已，0未）

                #region 图片上传方法 现在布传图片
                //HttpFileCollection files = context.Request.Files;
                //if (files.Count > 0)
                //{
                //    Random rnd = new Random();
                //    for (int i = 0; i < files.Count; i++)
                //    {
                //        HttpPostedFile file = files[i];
                //        var len = file.ContentLength;
                //        if (len > 0)
                //        {
                //            string fileName = file.FileName;
                //            string extension = Path.GetExtension(fileName);
                //            if (extension.ToLower() == ".jpg" || extension.ToLower() == ".bmp" || extension.ToLower() == ".gif" || extension.ToLower() == ".png")
                //            {
                //                string PhotoMaxSize = System.Configuration.ConfigurationManager.AppSettings["PhotoMaxSize"];
                //                if (len > int.Parse(PhotoMaxSize) * 1024)
                //                {
                //                    continue;
                //                }


                //                var FileDown = id + extension;
                //                var Folder = System.DateTime.Now.ToString("yyyyMM");
                //                if (System.IO.Directory.Exists(System.Web.HttpContext.Current.Request.MapPath("../../Upload/Photo/" + Folder)) == false)//如果不存在就创建file文件夹
                //                {
                //                    System.IO.Directory.CreateDirectory(System.Web.HttpContext.Current.Request.MapPath("../../Upload/Photo/" + Folder));
                //                }
                //                //保存文件
                //                var SaveImgPath = System.Web.HttpContext.Current.Request.MapPath("../../Upload/Photo/" + Folder + "/") + FileDown;
                //                Common.MakeThumNail(System.Drawing.Image.FromStream(file.InputStream), SaveImgPath, 90, 120, "HW"); ; //照片
                //                mMsjZaYqbz.Zp = "/Upload/Photo/" + Folder + "/" + FileDown; //照片                                
                //            }
                //            //int num = rnd.Next(5000, 10000);
                //            //string path = "file/" + num.ToString() + extension;
                //            //file.SaveAs(System.Web.HttpContext.Current.Server.MapPath(path));
                //        }
                //    }
                //}
                #endregion

                mResultModel = MsjZaYqbzBLL.Insert(mMsjZaYqbz, context.Session["UserID"], true); //新建操作
                context.Response.Write(JsonConvert.SerializeObject(mResultModel)); //序列化后返回
            }
            catch (Exception ex)
            {
                MSEx.DealErr(ex, "");
                mResultModel.ErrorCode = -9999;
                mResultModel.ISSucceed = false;
                context.Response.Write(JsonConvert.SerializeObject(mResultModel)); //序列化后返回
            }
        }
        #endregion

        #region 删除记录
        /// <summary>
        /// 删除记录
        /// </summary>
        protected void DeleteRecord()
        {

            HttpContext context = HttpContext.Current;
            context.Response.ContentType = "text/plain";
            ResultModel mResultModel = new ResultModel(); //声明返回类型
            try
            {
                string[] arryParamKey = context.Request.Params["id"].ToString().Split(',');
                if (arryParamKey.Length == 0)
                {
                    mResultModel.ErrorCode = -9991;
                    mResultModel.ISSucceed = false;
                    context.Response.Write(JsonConvert.SerializeObject(mResultModel)); //序列化后返回    
                    return;
                }
                MsjZaYqbz mMsjZaYqbz = new MsjZaYqbz();
                foreach (var paramKey in arryParamKey)
                {
                    mResultModel = MsjZaYqbzBLL.Delete(paramKey, context.Session["UserID"], true); //删除对应的信息
                }
                context.Response.Write(JsonConvert.SerializeObject(mResultModel)); ; //序列化后返回
            }
            catch (Exception ex)
            {
                MSEx.DealErr(ex, ""); //写入异常日志
                mResultModel.ErrorCode = -9999; //-9999代码是系统异常通用代码
                mResultModel.ISSucceed = false; //行为执行失败
                context.Response.Write(JsonConvert.SerializeObject(mResultModel)); //序列化后返回
            }

        }
        #endregion

        #region 修改记录
        /// <summary>
        /// 修改记录
        /// </summary>
        protected void EditRecord()
        {
            HttpContext context = HttpContext.Current;
            context.Response.ContentType = "text/plain";
            ResultModel mResultModel = new ResultModel(); //初始化返回类型
            MsjZaYqbz mMsjZaYqbz = new MsjZaYqbz();
            //对Session的处理
            var mUser = AppOrganizatiOnUserBLL.Load(context.Session["UserID"].ToString());
            var mOrg = AppOrganizatiOnBLL.Load(mUser.OrgnaId);

            string paramKey = context.Request.Params["id"];
            try
            {

                if (string.IsNullOrEmpty(paramKey))
                {
                    mResultModel.ErrorCode = -9991;
                    mResultModel.ISSucceed = false;
                    context.Response.Write(JsonConvert.SerializeObject(mResultModel)); //序列化后返回    
                    return;
                }
                mMsjZaYqbz = MsjZaYqbzBLL.Load(paramKey); //根据键值获取实体信息
                if (mMsjZaYqbz != null)
                {
                    mMsjZaYqbz.Xm = context.Request.Form["texXm"]; //养犬人姓名
                    mMsjZaYqbz.Zw = context.Request.Form["texZw"]; //联系电话
                    mMsjZaYqbz.Sfzh = context.Request.Form["texSfzh"]; //身份证号
                    mMsjZaYqbz.Email = context.Request.Form["texEmail"]; //Email地址
                    mMsjZaYqbz.Yqrzz = context.Request.Form["texYqrzz"]; //养犬人住址(请精确到门牌号码）
                    mMsjZaYqbz.Sjdwid = context.Request.Form["texSjdwid"]; //上级单位ID(所属分局和市局）
                    mMsjZaYqbz.Pcsid = context.Request.Form["texPcsid"]; //单位ID
                    mMsjZaYqbz.Qz = context.Request.Form["texQz"]; //犬种
                    mMsjZaYqbz.Ms = context.Request.Form["texMs"]; //毛色
                    mMsjZaYqbz.Jg = Convert.ToDecimal(context.Request.Form["texJg"]); //肩高(cm)
                    mMsjZaYqbz.Tc = Convert.ToDecimal(context.Request.Form["texTc"]); //体长(cm)
                    mMsjZaYqbz.Xb = context.Request.Form["selXb"]; //犬只性别（1雄，0雌）
                    mMsjZaYqbz.Qm = context.Request.Form["texQm"]; //犬名
                    //mMsjZaYqbz.Zp = context.Request.Form["texZp"]; //犬只照片
                    mMsjZaYqbz.Xgsj = DateTime.Now.ToString(); //创建时间(2013-05-28 09:13:01)
                    mMsjZaYqbz.Xgr = mUser.AreaId; //创建人(人员ID)
                    mMsjZaYqbz.Xgrdw = mOrg.OrgnaCode; //创建单位(单位ID)
                    mMsjZaYqbz.Enabled = Enabled.TRUE; //是否有效（1有效，0无效）
                    mMsjZaYqbz.Movesign = "0"; //是否传输（1已，0未）

                    mResultModel = MsjZaYqbzBLL.Update(mMsjZaYqbz, context.Session["UserID"], true); //新建操作
                }
                else
                {
                    mResultModel.ErrorCode = -9990; //没有获取所需的信息，信息可能已被删除
                    mResultModel.ISSucceed = false;

                }
                context.Response.Write(JsonConvert.SerializeObject(mResultModel)); //序列化后返回
            }
            catch (Exception ex)
            {
                MSEx.DealErr(ex, "");
                mResultModel.ErrorCode = -9999;
                mResultModel.ISSucceed = false;
                context.Response.Write(JsonConvert.SerializeObject(mResultModel)); //序列化后返回
            }
        }
        #endregion

        #region 获取实体记录
        /// <summary>
        /// 获取实体记录
        /// </summary>
        protected void GetModel()
        {
            HttpContext context = HttpContext.Current;
            context.Response.ContentType = "text/plain";
            ResultModel mResultModel = new ResultModel(); //初始化返回类型
            string paramKey = context.Request.Params["id"];
            string json = "";
            try
            {
                MsjZaYqbz mMsjZaYqbz = new MsjZaYqbz(); //声明实体
                if (!string.IsNullOrEmpty(paramKey))
                {
                    mMsjZaYqbz = MsjZaYqbzBLL.Load(paramKey); //根据键值获取管理员
                    if (mMsjZaYqbz != null)
                    {
                        mMsjZaYqbz.Xbstr = mMsjZaYqbz.Xb == "1" ? "雄性" : " 雌性";
                        json = JsonConvert.SerializeObject(mMsjZaYqbz);
                    }
                }
            }
            catch (Exception ex)
            {
                MSEx.DealErr(ex, "");
                mResultModel.ErrorCode = -9990;
                mResultModel.ISSucceed = false;
                json = JsonConvert.SerializeObject(mResultModel);
            }
            context.Response.Write(json);
        }
        #endregion

        #region 获取数据
        /// <summary>
        /// 获取数据记录
        /// </summary>
        protected void QueryRecord()
        {
            TableMessage tm = new TableMessage();
            HearderMessage hm = new HearderMessage();
            List<HearderMessage> list = new List<HearderMessage>();
            HttpContext context = HttpContext.Current;
            context.Response.ContentType = "text/plain";
            string pageSize = context.Request.Form["pageSize"];
            string pageIndex = context.Request.Form["pageIndex"];
            string name = context.Request.Form["texName"];
            string dogKind = context.Request.Form["texQz"];
            string timeStart = context.Request.Form["texTimeStart"];
            string timeEnd = context.Request.Form["texTimeEnd"];
            if (String.IsNullOrEmpty(pageSize) || String.IsNullOrEmpty(pageIndex) || !AnyString.IsNumeric(pageSize) || !AnyString.IsNumeric(pageIndex))
                return;
            DataTable dtMsjZaYqbz = new DataTable();
            int intPageSize = Convert.ToInt32(pageSize);
            int intPageIndex = Convert.ToInt32(pageIndex);
            QueryByPage Q = new QueryByPage();
            SqlConditionList sqllist = new SqlConditionList();
            string sqlWhere = " enabled='1' ";
            if (!string.IsNullOrEmpty(name)) ////姓名
            {
                sqllist.AddLogic(new SqlConditionList.SqlCondition(SqlCompareOper.LIKE, MsjZaYqbzConst.Columns.Xm, '%' + name + '%'), SqlLogicOper.AND_LOGIC);
            }
            if (!string.IsNullOrEmpty(dogKind)) ////犬种
            {
                sqllist.AddLogic(new SqlConditionList.SqlCondition(SqlCompareOper.LIKE, MsjZaYqbzConst.Columns.Qz, '%' + dogKind + '%'), SqlLogicOper.AND_LOGIC);
            }

            if (!string.IsNullOrEmpty(timeStart)) ////添加时间-开始
            {
                sqllist.AddLogic(new SqlConditionList.SqlCondition(SqlCompareOper.NOT_LESS_THAN, MsjZaYqbzConst.Columns.Cjsj, Convert.ToDateTime(timeStart)), SqlLogicOper.AND_LOGIC);
            }
            if (!string.IsNullOrEmpty(timeEnd)) ////添加时间-结束
            {
                sqllist.AddLogic(new SqlConditionList.SqlCondition(SqlCompareOper.NOT_MORE_THAN, MsjZaYqbzConst.Columns.Cjsj, Convert.ToDateTime(timeEnd)), SqlLogicOper.AND_LOGIC);
            }

            if (string.IsNullOrEmpty(sqllist.ToSql()))
            {
                sqlWhere = "where" + sqlWhere;
            }
            else
            {
                sqlWhere = sqllist.ToSql() + " and " + sqlWhere;
            }
            dtMsjZaYqbz = Q.GetRecordByPage("RYID,XM,ZW,SFZH,QZ,TC,CJSJ", sqlWhere, "CJSJ", intPageSize, intPageIndex, MsjZaYqbzConst.TableName, MsjZaYqbzConst.FieldKey, "desc").Tables[0];
            if (dtMsjZaYqbz != null && dtMsjZaYqbz.Rows.Count > 0)
            {
                for (int i = 0; i < dtMsjZaYqbz.Columns.Count; i++)
                {
                    hm = new HearderMessage();
                    hm.name = dtMsjZaYqbz.Columns[i].Caption;
                    list.Add(hm);
                }
                tm.Header = list;
                tm.data = dtMsjZaYqbz;
                tm.totalCount = Convert.ToString((int)Q.RowCount);
            }
            string json = JsonConvert.SerializeObject(tm);
            context.Response.Write(json);
        }
        #endregion

    }
}


